/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiof.moraa.server.dao;

import com.hiof.moraa.mapping.TblAthlete;
import com.hiof.moraa.mapping.TblSupport;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Bergy
 */
public class HibernateAthleteDAOImp implements AthleteDAO {

    private SessionFactory factory;

    public SessionFactory getFactory() {
        return factory;
    }

    public void setFactory(SessionFactory factory) {
        this.factory = factory;
    }

    @Override
    public TblAthlete getAthleteById(int athleteId) {
        TblAthlete athlete = (TblAthlete) factory.getCurrentSession().get(TblAthlete.class, athleteId);
        return athlete;
    }

    @Override
    public List<TblAthlete> getTeamMember(int teamId) {
        Session session = factory.getCurrentSession();
        String hql = "from TblAthlete athlete where athlete.tblTeam.id = :teamId";
        Query query = session.createQuery(hql);
        query.setParameter("teamId", teamId);
        return query.list();
    }

    @Override
    public List<TblSupport> getSupports(int athleteId) {
        Session session = factory.getCurrentSession();
        int teamId = ((TblAthlete) session.get(TblAthlete.class, athleteId)).getTblTeam().getId();
        String hql = "from TblSupport support where support.tblTeam.id = :teamId";
        Query query = session.createQuery(hql);
        query.setInteger("teamId", teamId);
        return query.list();
    }

    @Override
    public TblAthlete getAthleteByUserIdAndRouteId(int userId, int routeId) {
        Session session = factory.getCurrentSession();
        String hql = "from TblAthlete athlete where athlete.tblUser.id = :userId and athlete.tblRoute.id = :routeId";
        Query query = session.createQuery(hql);
        query.setInteger("userId", userId);
        query.setInteger("routeId", routeId);
        return (TblAthlete)query.uniqueResult();
    }

    @Override
    public TblAthlete getAthleteByUsernameAndRouteId(String username, int routeId) {
        Session session = factory.getCurrentSession();
        String hql = "from TblAthlete athlete where athlete.tblUser.username = :username and athlete.tblRoute.id = :routeId";
        Query query = session.createQuery(hql);
        query.setString("username", username);
        query.setInteger("routeId", routeId);
        return (TblAthlete)query.uniqueResult();
    }
}
